<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能农业大棚监控系统</title>
    
    <!-- 国内CDN资源 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/daisyui/4.12.10/full.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/Chart.js/4.4.0/chart.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.6.7/axios.min.js"></script>
    
    <style>
        .status-online { color: #10b981; }
        .status-offline { color: #ef4444; }
        .chart-container { position: relative; height: 300px; }
        .sensor-card { transition: all 0.3s ease; }
        .sensor-card:hover { transform: translateY(-2px); }
    </style>
</head>
<body class="bg-gray-50">
    <div class="container mx-auto px-4 py-6">
        <!-- 页面标题 -->
        <div class="text-center mb-8">
            <h1 class="text-4xl font-bold text-green-600 mb-2">
                <i class="fas fa-seedling mr-3"></i>智能农业大棚监控系统
            </h1>
            <p class="text-gray-600">实时监控 · 智能控制 · 数据分析</p>
        </div>

        <!-- 系统状态概览 -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div class="stats shadow bg-white">
                <div class="stat">
                    <div class="stat-figure text-primary">
                        <i class="fas fa-network-wired text-3xl"></i>
                    </div>
                    <div class="stat-title">总节点数</div>
                    <div class="stat-value text-primary" id="total-nodes">0</div>
                </div>
            </div>
            
            <div class="stats shadow bg-white">
                <div class="stat">
                    <div class="stat-figure text-success">
                        <i class="fas fa-wifi text-3xl"></i>
                    </div>
                    <div class="stat-title">在线节点</div>
                    <div class="stat-value text-success" id="online-nodes">0</div>
                </div>
            </div>
            
            <div class="stats shadow bg-white">
                <div class="stat">
                    <div class="stat-figure text-warning">
                        <i class="fas fa-thermometer-half text-3xl"></i>
                    </div>
                    <div class="stat-title">平均温度</div>
                    <div class="stat-value text-warning" id="avg-temp">--°C</div>
                </div>
            </div>
            
            <div class="stats shadow bg-white">
                <div class="stat">
                    <div class="stat-figure text-info">
                        <i class="fas fa-tint text-3xl"></i>
                    </div>
                    <div class="stat-title">平均湿度</div>
                    <div class="stat-value text-info" id="avg-humidity">--%</div>
                </div>
            </div>
        </div>

        <!-- 控制面板 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
            <!-- 作物模板选择 -->
            <div class="card bg-white shadow-xl">
                <div class="card-body">
                    <h2 class="card-title">
                        <i class="fas fa-leaf text-green-500"></i>
                        作物模板
                    </h2>
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text">选择作物类型</span>
                        </label>
                        <select class="select select-bordered" id="crop-template">
                            <option value="tomato">🍅 番茄</option>
                            <option value="strawberry">🍓 草莓</option>
                            <option value="general">🌱 通用</option>
                        </select>
                    </div>
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text">目标节点</span>
                        </label>
                        <select class="select select-bordered" id="target-node">
                            <option value="1">节点 1</option>
                        </select>
                    </div>
                    <button class="btn btn-primary" onclick="applyTemplate()">
                        <i class="fas fa-magic mr-2"></i>应用模板
                    </button>
                </div>
            </div>

            <!-- 手动控制 -->
            <div class="card bg-white shadow-xl">
                <div class="card-body">
                    <h2 class="card-title">
                        <i class="fas fa-sliders-h text-blue-500"></i>
                        手动控制
                    </h2>
                    <div class="form-control">
                        <label class="label cursor-pointer">
                            <span class="label-text">水泵</span>
                            <input type="checkbox" class="toggle toggle-primary" id="pump-toggle">
                        </label>
                    </div>
                    <div class="form-control">
                        <label class="label cursor-pointer">
                            <span class="label-text">加热灯</span>
                            <input type="checkbox" class="toggle toggle-secondary" id="heater-toggle">
                        </label>
                    </div>
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text">目标节点</span>
                        </label>
                        <select class="select select-bordered" id="control-node">
                            <option value="1">节点 1</option>
                        </select>
                    </div>
                    <button class="btn btn-secondary" onclick="sendControlCommand()">
                        <i class="fas fa-paper-plane mr-2"></i>发送命令
                    </button>
                </div>
            </div>

            <!-- 报警状态 -->
            <div class="card bg-white shadow-xl">
                <div class="card-body">
                    <h2 class="card-title">
                        <i class="fas fa-exclamation-triangle text-red-500"></i>
                        报警状态
                    </h2>
                    <div id="alarm-status" class="space-y-2">
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle"></i>
                            <span>系统运行正常</span>
                        </div>
                    </div>
                    <button class="btn btn-ghost btn-sm" onclick="refreshAlarms()">
                        <i class="fas fa-sync-alt mr-2"></i>刷新状态
                    </button>
                </div>
            </div>
        </div>

        <!-- 数据图表 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <!-- 温度趋势图 -->
            <div class="card bg-white shadow-xl">
                <div class="card-body">
                    <h2 class="card-title">
                        <i class="fas fa-chart-line text-red-500"></i>
                        温度趋势
                    </h2>
                    <div class="chart-container">
                        <canvas id="temp-chart"></canvas>
                    </div>
                </div>
            </div>

            <!-- 湿度趋势图 -->
            <div class="card bg-white shadow-xl">
                <div class="card-body">
                    <h2 class="card-title">
                        <i class="fas fa-chart-area text-blue-500"></i>
                        湿度趋势
                    </h2>
                    <div class="chart-container">
                        <canvas id="humidity-chart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- 节点详情 -->
        <div class="card bg-white shadow-xl">
            <div class="card-body">
                <h2 class="card-title">
                    <i class="fas fa-info-circle text-info"></i>
                    节点详情
                </h2>
                <div class="overflow-x-auto">
                    <table class="table table-zebra w-full">
                        <thead>
                            <tr>
                                <th>节点ID</th>
                                <th>状态</th>
                                <th>土壤温度(°C)</th>
                                <th>土壤湿度(%)</th>
                                <th>CO2浓度(ppm)</th>
                                <th>光照强度(lux)</th>
                                <th>水泵</th>
                                <th>加热灯</th>
                                <th>最后更新</th>
                            </tr>
                        </thead>
                        <tbody id="nodes-table">
                            <tr>
                                <td colspan="9" class="text-center text-gray-500">
                                    <i class="fas fa-spinner fa-spin mr-2"></i>加载中...
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="footer footer-center p-4 bg-base-300 text-base-content mt-8">
        <div>
            <p>智能农业大棚监控系统 © 2024 - 基于STM32 + Flask</p>
        </div>
    </footer>

    <script>
        // 全局变量
        let tempChart, humidityChart;
        let dataHistory = {
            timestamps: [],
            temperatures: [],
            humidities: []
        };
        let maxDataPoints = 20;

        // 初始化图表
        function initCharts() {
            const chartOptions = {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: true,
                        position: 'top'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: false
                    }
                }
            };

            // 温度图表
            const tempCtx = document.getElementById('temp-chart').getContext('2d');
            tempChart = new Chart(tempCtx, {
                type: 'line',
                data: {
                    labels: dataHistory.timestamps,
                    datasets: [{
                        label: '土壤温度 (°C)',
                        data: dataHistory.temperatures,
                        borderColor: 'rgb(239, 68, 68)',
                        backgroundColor: 'rgba(239, 68, 68, 0.1)',
                        tension: 0.4
                    }]
                },
                options: chartOptions
            });

            // 湿度图表
            const humidityCtx = document.getElementById('humidity-chart').getContext('2d');
            humidityChart = new Chart(humidityCtx, {
                type: 'line',
                data: {
                    labels: dataHistory.timestamps,
                    datasets: [{
                        label: '土壤湿度 (%)',
                        data: dataHistory.humidities,
                        borderColor: 'rgb(59, 130, 246)',
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        tension: 0.4
                    }]
                },
                options: chartOptions
            });
        }

        // 更新图表数据
        function updateChartData(data) {
            const now = new Date().toLocaleTimeString();
            
            dataHistory.timestamps.push(now);
            dataHistory.temperatures.push(data.soil_temp);
            dataHistory.humidities.push(data.soil_humidity);
            
            // 保持数据点数量
            if (dataHistory.timestamps.length > maxDataPoints) {
                dataHistory.timestamps.shift();
                dataHistory.temperatures.shift();
                dataHistory.humidities.shift();
            }
            
            // 更新图表
            tempChart.data.labels = dataHistory.timestamps;
            tempChart.data.datasets[0].data = dataHistory.temperatures;
            tempChart.update();
            
            humidityChart.data.labels = dataHistory.timestamps;
            humidityChart.data.datasets[0].data = dataHistory.humidities;
            humidityChart.update();
        }

        // 获取系统数据
        async function fetchData() {
            try {
                const response = await axios.get('/api/data');
                const data = response.data;
                
                // 更新系统状态
                document.getElementById('total-nodes').textContent = data.system_status.total_nodes;
                document.getElementById('online-nodes').textContent = data.system_status.online_nodes;
                
                // 计算平均值
                let totalTemp = 0, totalHumidity = 0, count = 0;
                for (const nodeId in data.nodes) {
                    const node = data.nodes[nodeId];
                    if (node.status === 'online') {
                        totalTemp += node.soil_temp;
                        totalHumidity += node.soil_humidity;
                        count++;
                    }
                }
                
                if (count > 0) {
                    document.getElementById('avg-temp').textContent = (totalTemp / count).toFixed(1) + '°C';
                    document.getElementById('avg-humidity').textContent = (totalHumidity / count).toFixed(1) + '%';
                }
                
                // 更新节点表格
                updateNodesTable(data.nodes);
                
                // 更新图表（如果有在线节点）
                if (count > 0) {
                    const firstNode = Object.values(data.nodes)[0];
                    updateChartData(firstNode);
                }
                
            } catch (error) {
                console.error('获取数据失败:', error);
            }
        }

        // 更新节点表格
        function updateNodesTable(nodes) {
            const tbody = document.getElementById('nodes-table');
            tbody.innerHTML = '';
            
            if (Object.keys(nodes).length === 0) {
                tbody.innerHTML = '<tr><td colspan="9" class="text-center text-gray-500">暂无节点数据</td></tr>';
                return;
            }
            
            for (const nodeId in nodes) {
                const node = nodes[nodeId];
                const statusClass = node.status === 'online' ? 'status-online' : 'status-offline';
                const statusIcon = node.status === 'online' ? 'fa-wifi' : 'fa-wifi-slash';
                const pumpStatus = node.pump_status ? '<span class="badge badge-success">开启</span>' : '<span class="badge badge-error">关闭</span>';
                const heaterStatus = node.heater_status ? '<span class="badge badge-success">开启</span>' : '<span class="badge badge-error">关闭</span>';
                const lastUpdate = new Date(node.timestamp * 1000).toLocaleTimeString();
                
                const row = `
                    <tr class="sensor-card">
                        <td>${node.node_id}</td>
                        <td><span class="${statusClass}"><i class="fas ${statusIcon} mr-1"></i>${node.status === 'online' ? '在线' : '离线'}</span></td>
                        <td>${node.soil_temp.toFixed(1)}</td>
                        <td>${node.soil_humidity.toFixed(1)}</td>
                        <td>${node.co2}</td>
                        <td>${node.light.toLocaleString()}</td>
                        <td>${pumpStatus}</td>
                        <td>${heaterStatus}</td>
                        <td>${lastUpdate}</td>
                    </tr>
                `;
                tbody.innerHTML += row;
            }
        }

        // 应用作物模板
        async function applyTemplate() {
            const template = document.getElementById('crop-template').value;
            const nodeId = document.getElementById('target-node').value;
            
            try {
                const response = await axios.post(`/api/templates/${template}`, {
                    node_id: nodeId
                });
                
                if (response.data.status === 'success') {
                    alert(`成功应用${response.data.template.name}模板到节点${nodeId}`);
                }
            } catch (error) {
                alert('应用模板失败: ' + error.message);
            }
        }

        // 发送控制命令
        async function sendControlCommand() {
            const nodeId = document.getElementById('control-node').value;
            const pumpStatus = document.getElementById('